//
//  SQPhotosView.m
//  ambition
//
//  Created by 苏青 on 2019/11/28.
//  Copyright © 2019 苏青. All rights reserved.
//

#import "SQPhotosView.h"
#import "MLSelectPhotoAssets.h"
#import "MLSelectPhotoPickerAssetsViewController.h"
#import "MLSelectPhotoBrowserViewController.h"
#import "SDAutoLayout.h"

@implementation SQPhotosView

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
//    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, HEIGHT(116) );
    [self config];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, HEIGHT(116) );
        [self config];
        
    }
    return self;
}

-(void)config{
    
    self.btn_space = 10;
    self.btn_width = W(60) ;
    self.btn_height = W(60) ;
    self.btn_max = 5;
    
    self.photosArr = [[NSMutableArray alloc]init];
    
    [self createBtns];
}


-(void)reloadView:(NSArray *)imgArr{
    self.photosArr = [[NSMutableArray alloc]initWithArray:imgArr];
    [self createBtns];
}
-(void)createBtns{
    
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    
    int count = (int)self.photosArr.count;
    
    
    for (int i = 0 ; i < count+1; i++) {
        
        if (count >= i+1) {
            
            UIView *img_view = [[UIView alloc]initWithFrame:CGRectMake(self.btn_space*(i%3) + i%3 * self.btn_width, self.btn_space*(i/3) + i/3 * self.btn_height  , self.btn_width, self.btn_height)];
            img_view.layer.cornerRadius = 4 ;
            img_view.clipsToBounds = YES;
            
            UIImageView *img = [[UIImageView alloc]initWithFrame:img_view.bounds];
            
            id im = self.photosArr[i];
            if ([im isKindOfClass:[UIImage class] ]) {
                [img setImage:self.photosArr[i]];
            }else{
                [img SQ_setImageWithURL:self.photosArr[i] placeholder:@"sit"];
            }
            
            [img_view addSubview:img];
            [self addSubview:img_view];
            
            self.height_sd = img_view.top_sd + img_view.height_sd;
            
            if (self.block) {
                UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                [closeBtn setFrame:CGRectMake(self.btn_width-24, 2, 22, 22)];
                [closeBtn addTarget:self action:@selector(deleteImg:) forControlEvents:UIControlEventTouchUpInside];
                [closeBtn setImage:[UIImage imageNamed:@"del.png"] forState:UIControlStateNormal];
                closeBtn.tag = i;
                
                [img_view addSubview:closeBtn];
                
            }else{
                img.tag = i;
                [img setUserInteractionEnabled:YES];
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Imagesbrowser:)];
                [img addGestureRecognizer:tap];
            }
            
        }else if(i < self.btn_max){
            
            if (self.block) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                
                [btn setFrame:CGRectMake(self.btn_space*(i%3) + i%3 * self.btn_width, self.btn_space*(i/3) + i/3 * self.btn_height  , self.btn_width, self.btn_height)];
                [btn setImage:[UIImage imageNamed:self.addImgName?self.addImgName:@"add.png"] forState:UIControlStateNormal];
                btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
                [btn addTarget:self action:@selector(ChooseImageWay) forControlEvents:UIControlEventTouchUpInside];
                
                [self addSubview:btn];
                
                self.height_sd = btn.top_sd + btn.height_sd;
            }
        }
        
    }
    
    
}
-(void)deleteImg:(UIButton *)sender{
    
    [self.photosArr removeObjectAtIndex:sender.tag];
    [self createBtns];
    
    __weak typeof(self) weakSelf = self;
    if(self.block){
        self.block(weakSelf.photosArr);
    }
}

-(void)ChooseImageWay{
    
   UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册获取", nil];
    [sheet showInView:self.VC.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        
        [self readFromcamera];
        
    }else if (buttonIndex == 1){
        
        [self selectPhotos];
    }
    
}

-(void)Imagesbrowser:(UITapGestureRecognizer *)tap{
    
    int index = (int)tap.view.tag;
    
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.currentImageIndex = index;
    browser.sourceImagesContainerView = self;
    browser.imageCount = self.photosArr.count;
    browser.delegate = self;
    
    [browser show];
}
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    return [UIImage imageNamed:@""];
}
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    
    return [NSURL URLWithString:[NSString stringWithFormat:@"%@", self.photosArr[index]]];
    
}

#pragma mark - 选择相册
- (void)selectPhotos {
    // 创建控制器
    MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
    // 默认显示相册里面的内容SavePhotos
    // 默认最多能选5张图片
    pickerVc.maxCount = self.btn_max - self.photosArr.count;
    pickerVc.status = PickerViewShowStatusCameraRoll;
    [pickerVc showPickerVc:self.VC];
    __weak typeof(self) weakSelf = self;
    pickerVc.callBack = ^(NSArray *assets){
        
        if (assets.count > 0) {
            
            for (MLSelectPhotoAssets *asset in assets) {
                UIImage *img =  [MLSelectPhotoPickerViewController getImageWithImageObj:asset];
                [weakSelf.photosArr addObject:img];
            }
            
            [weakSelf createBtns];
            
            if(self.block){
                self.block(weakSelf.photosArr);
            }
        }
        
    };
}

#pragma mark -选择相机
-(void)readFromcamera
{
    
    if ((YES == [UIImagePickerController isSourceTypeAvailable:
                 UIImagePickerControllerSourceTypeCamera])
        )
    {
        
        UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
        cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        cameraUI.mediaTypes =
        [UIImagePickerController availableMediaTypesForSourceType:
         UIImagePickerControllerSourceTypeCamera];
        
        cameraUI.allowsEditing = YES;
        
        cameraUI.delegate = self;
        
        [self.VC presentViewController:cameraUI animated:YES completion:nil];
        
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"打开照相机失败了" message:@"请检查照相机是否已损坏" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil];
        [alert show];
        
    }
    
}
#pragma mark UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    UIImage *originalImage, *editedImage;
    
    if ([mediaType isEqualToString:@"public.image"]){
        
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];
        
        
        //  NSData *imageData= UIImageJPEGRepresentation(editedImage, 100);
        //    NSData*  imageData = UIImagePNGRepresentation(editedImage);
        
        // photoImageView.image = [UIImage imageWithData:imageData];
        
        [self.photosArr addObject:editedImage];
        [self createBtns];
        
         __weak typeof(self) weakSelf = self;
        if(self.block){
            self.block(weakSelf.photosArr);
        }
        
    }
    
    [_VC dismissViewControllerAnimated: YES completion:nil];
    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [_VC dismissViewControllerAnimated:YES completion:nil];//退出
}



@end
